/*
 * This file Copyright (c) 2015. Walle.
 * (http://www.wallellen.com). All rights reserved.
 *
 *
 * This file is dual-licensed under both the
 * Walle Agreement (WA) and the GNU General Public License.
 * You may elect to use one or the other of these licenses.
 *
 * This file is distributed in the hope that it will be
 * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
 * Redistribution, except as permitted by whichever of the GPL
 * or WA you select, is prohibited.
 *
 * 1. For the GPL license (GPL), you can redistribute and/or
 * modify this file under the terms of the GNU General
 * Public License, Version 3, as published by the Free Software
 * Foundation.  You should have received a copy of the GNU
 * General Public License, Version 3 along with this program;
 * if not, write to the Free Software Foundation, Inc., 51
 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * 2. For the Walle Agreement (WA), this file
 * and the accompanying materials are made available under the
 * terms of the WA which accompanies this distribution, and
 * is available at http://www.wallellen.com/agreement.html
 *
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 */

package com.wallellen.knowledge.web.controller;

import com.wallellen.core.auth.domain.LoginUser;
import com.wallellen.core.page.ViewMode;
import com.wallellen.core.sql.result.DataResult;
import com.wallellen.knowledge.doc.domain.DocRunInfo;
import com.wallellen.knowledge.doc.domain.DocText;
import com.wallellen.knowledge.doc.domain.DocType;
import com.wallellen.knowledge.doc.domain.Docfile;
import com.wallellen.knowledge.doc.domain.ex.DocBrief;
import com.wallellen.knowledge.doc.domain.ex.DocEntire;
import com.wallellen.knowledge.doc.exception.CanNoReadException;
import com.wallellen.knowledge.doc.exception.DocNoExistException;
import com.wallellen.knowledge.doc.server.DocIndexInter;
import com.wallellen.knowledge.doc.server.DocManagerInter;
import com.wallellen.knowledge.doc.server.DocOperateRightInter;
import com.wallellen.knowledge.doc.server.DocRunInfoInter;
import com.wallellen.knowledge.doc.server.DocmessageManagerInter;
import com.wallellen.knowledge.doc.server.FileManagerInter;
import com.wallellen.knowledge.web.util.ThemesUtil;
import com.wallellen.web.WebUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;


@RequestMapping("/webdoc")
@Controller
public class DocController extends WebUtils {
    @Resource
    private FileManagerInter farmFileManagerImpl;
    @Resource
    private DocManagerInter farmDocManagerImpl;
    @Resource
    private DocRunInfoInter farmDocRunInfoImpl;
    @Resource
    private DocmessageManagerInter farmDocmessageManagerImpl;
    @Resource
    private DocOperateRightInter farmDocOperateRightImpl;
    @Resource
    private DocIndexInter farmDocIndexManagerImpl;

    /**
     * 查看文档
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/view/Pub{docid}", method = RequestMethod.GET)
    public ModelAndView showDoc(@PathVariable("docid") String docid, HttpSession session, HttpServletRequest request)
            throws Exception {
        ViewMode page = ViewMode.getInstance();
        try {
            DocEntire doc = farmDocManagerImpl.getDoc(docid, getCurrentUser(session));
            page.putAttr("DOCE", doc);
            List<DocText> versions = farmDocManagerImpl.getDocVersions(docid);
            page.putAttr("VERSIONS", versions);
            if (getCurrentUser(session) != null) {
                boolean isenjoy = farmDocRunInfoImpl.isEnjoyDoc(getCurrentUser(session).getId(), docid);
                page.putAttr("ISENJOY", isenjoy);
            }
            DocType type = doc.getType();
            page.putAttr("TYPEID", type == null ? "" : type.getId());
            Set<String> fileTypes = new HashSet<>();
            for (Docfile node : doc.getFiles()) {
                fileTypes.add(node.getExname().trim().replace(".", "").toUpperCase());
            }
            page.putAttr("FILETYPES", fileTypes);
            farmDocRunInfoImpl.visitDoc(docid, getCurrentUser(session), getCurrentIp(request));
            LoginUser user = getCurrentUser(session);
            if (type != null) {
                List<DocBrief> typedocs = farmDocRunInfoImpl.getTypeDocs(type == null ? "" : type.getId(),
                        user == null ? "none" : user.getId(), 10);
                page.putAttr("TYPEDOCS", typedocs);
            }
            List<DocBrief> relationdocs = farmDocIndexManagerImpl.getRelationDocs(docid, 10);
            page.putAttr("RELATIONDOCS", relationdocs);
            if (doc.getDoc().getDomtype().equals("1")) {
                return page.returnModelAndView(ThemesUtil.getThemePath() + "/know/view");
            }
            if (doc.getDoc().getDomtype().equals("5")) {
                return page.returnModelAndView(ThemesUtil.getThemePath() + "/webfile/webfile");
            }
            if (doc.getDoc().getDomtype().equals("4")) {
                return page.putAttr("groupid", doc.getGroup().getId()).returnRedirectUrl("/webgroup/Pubshow.do");
            }
        } catch (CanNoReadException e) {
            return ViewMode.getInstance().setError(e.toString()).returnModelAndView(ThemesUtil.getThemePath() + "/error");
        } catch (DocNoExistException e) {
            return ViewMode.getInstance().setError(e.toString()).returnModelAndView(ThemesUtil.getThemePath() + "/error");
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e.toString()).returnModelAndView(ThemesUtil.getThemePath() + "/error");
        }
        return ViewMode.getInstance().setError("请实现正确的DOCTYPE类型解析").returnModelAndView(ThemesUtil.getThemePath() + "/error");
    }

    @RequestMapping("/enjoy")
    @ResponseBody
    public Map<String, Object> enjoy(HttpSession session, String id) {
        try {
            farmDocRunInfoImpl.enjoyDoc(getCurrentUser(session).getId(), id);
            return ViewMode.getInstance().putAttr("commitType", "0").returnObjMode();
        } catch (Exception e) {
            return ViewMode.getInstance().putAttr("commitType", "1").setError(e.getMessage()).returnObjMode();
        }
    }

    @RequestMapping("/FLunEnjoy")
    @ResponseBody
    public Map<String, Object> unenjoy(HttpSession session, String id) {
        try {
            farmDocRunInfoImpl.unEnjoyDoc(getCurrentUser(session).getId(), id);
            return ViewMode.getInstance().putAttr("commitType", "0").returnObjMode();
        } catch (Exception e) {
            return ViewMode.getInstance().putAttr("commitType", "1").setError(e.getMessage()).returnObjMode();
        }
    }

    @RequestMapping("/Pubmsg")
    public ModelAndView docMessage(Integer num, String docid, HttpSession session, HttpServletRequest request) {
        try {
            // 加载热词
            List<DocBrief> hotdocs = farmDocRunInfoImpl.getPubHotDoc(10);
            DocEntire doc = farmDocManagerImpl.getDoc(docid, getCurrentUser(session));
            if (num == null) {
                num = 1;
            }
            DataResult result = farmDocmessageManagerImpl.getMessages(docid, num, 20);
            for (Map<String, Object> map : result.getResultList()) {
                if (map.get("IMGID") != null) {
                    map.put("IMGURL", farmFileManagerImpl.getFileURL(map.get("IMGID").toString()));
                }
            }
            result.runformatTime("CTIME", "yyyy-MM-dd HH:mm:ss");

            return ViewMode.getInstance().putAttr("doc", doc).putAttr("hotdocs", hotdocs).putAttr("result", result)
                    .returnModelAndView(ThemesUtil.getThemePath() + "/know/docMessage");
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e.getMessage()).returnModelAndView(ThemesUtil.getThemePath() + "/error");
        }
    }

    @RequestMapping("/addmsg")
    public ModelAndView addMessage(String docid, String content, HttpSession session, HttpServletRequest request) {
        try {
            farmDocmessageManagerImpl.sendAnswering(content, "知识评论", "评论", docid, getCurrentUser(session));
            return ViewMode.getInstance().putAttr("docid", docid).returnRedirectUrl("/webdoc/Pubmsg.do");
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e.getMessage()).returnModelAndView(ThemesUtil.getThemePath() + "/error");
        }
    }

    @RequestMapping("/PubVersion")
    public ModelAndView showVersion(String textid, HttpSession session, HttpServletRequest request) {
        ViewMode page = ViewMode.getInstance();
        try {
            DocEntire doc = farmDocManagerImpl.getDocVersion(textid, getCurrentUser(session));
            if (!doc.getDoc().getState().equals("1")) {
                throw new RuntimeException("没有权限访问该文档");
            }
            List<DocText> versions = farmDocManagerImpl.getDocVersions(doc.getDoc().getId());
            page.putAttr("VERSIONS", versions);
            return page.putAttr("DOCE", doc).returnModelAndView(ThemesUtil.getThemePath() + "/know/version");
        } catch (Exception e) {
            return page.setError(e.getMessage()).returnModelAndView(ThemesUtil.getThemePath() + "/error");
        }
    }

    /**
     * 公开文档（将该文档开放阅读和编辑权限，同时如果是小组文档将删除小组所有权）
     *
     * @return
     */
    @RequestMapping("/FLflyKnow")
    public ModelAndView flyKnow(String id, HttpSession session) {
        try {
            farmDocOperateRightImpl.flyDoc(id, getCurrentUser(session));
            return ViewMode.getInstance().returnRedirectUrl("/webdoc/view/Pub" + id + ".html");
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e.toString()).returnModelAndView(ThemesUtil.getThemePath() + "/error");
        }
    }

    /**
     * 删除知识
     *
     * @return
     */
    @RequestMapping("/FLDelKnow")
    public ModelAndView delCommit(String id, HttpSession session) {
        try {
            farmDocManagerImpl.deleteDoc(id, getCurrentUser(session));
            return ViewMode.getInstance().putAttr("MESSAGE", "删除成功！")
                    .returnModelAndView(ThemesUtil.getThemePath() + "/message");
        } catch (Exception e) {
            e.printStackTrace();
            return ViewMode.getInstance().setError(e.toString()).returnModelAndView(ThemesUtil.getThemePath() + "/error");
        }
    }

    @RequestMapping("/delImg")
    public Map<String, Object> delImg(String imgid) {
        try {
            farmDocManagerImpl.delImg(imgid);
            return ViewMode.getInstance().returnObjMode();
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e.toString()).returnObjMode();
        }
    }

    @RequestMapping("/PubPraiseYes")
    @ResponseBody
    public Map<String, Object> praiseYes(String id, HttpSession session, HttpServletRequest request) {
        try {
            if (getCurrentUser(session) == null) {
                farmDocRunInfoImpl.praiseDoc(id, request.getRemoteAddr());
            } else {
                farmDocRunInfoImpl.praiseDoc(id, getCurrentUser(session), request.getRemoteAddr());
            }
            DocRunInfo runinfo = farmDocRunInfoImpl.loadRunInfo(id);
            return ViewMode.getInstance().putAttr("runinfo", runinfo).returnObjMode();
        } catch (Exception e) {
            e.printStackTrace();
            return ViewMode.getInstance().setError(e.toString()).returnObjMode();
        }
    }

    @RequestMapping("/PubPraiseNo")
    @ResponseBody
    public Map<String, Object> praiseNo(String id, HttpSession session, HttpServletRequest request) {
        try {
            if (getCurrentUser(session) == null) {
                farmDocRunInfoImpl.criticalDoc(id, getCurrentIp(request));
            } else {
                farmDocRunInfoImpl.criticalDoc(id, getCurrentUser(session), getCurrentIp(request));
            }
            DocRunInfo runinfo = farmDocRunInfoImpl.loadRunInfo(id);
            return ViewMode.getInstance().putAttr("runinfo", runinfo).returnObjMode();
        } catch (Exception e) {
            e.printStackTrace();
            return ViewMode.getInstance().setError(e.toString()).returnObjMode();
        }
    }
}
